/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdContentLibrary.h"
#include "tinyxml.h"
#include "hhdTScene.h"
#include "hhdTPrefab.h"

#if HHD_PLATFORM_WINDOWS
#include <crtdbg.h>
#include <Windows.h>
#endif //HHD_PLATFORM_WINDOWS

namespace hhd
{
    HashTable<String, SmartPtr<IContent> >* ContentLibrary::_content_table = NULL;
	HashTable< String, uint32_t > ContentLibrary::_type_to_id;
    uint32_t ContentLibrary::_num_types = 0;

    bool ContentLibrary::_given_env_var = false;
    String ContentLibrary::_content_path;

    Logger* ContentLibrary::_logger = NULL;

    void ContentLibrary::write(const char* in_message)
    {
        ContentLibrary::_logger->write(in_message);
    }

    bool ContentLibrary::prefabIsLoaded(const String& in_key)
    {
        SmartPtr<IContent> requested_prefab = NULL;
        _content_table[TPrefab::contentID()].tryGetValue(in_key, requested_prefab);
        if( requested_prefab )
        {
            return true;
        }

        return false;
    }

    void ContentLibrary::setContentPath(const String& in_path)
    {
        _content_path = in_path;
        _given_env_var = true;
    }

    String ContentLibrary::getCompleteContentString( const String& in_local_path )
    {
        if( !_given_env_var )
        {
            return in_local_path;
        }

        String result;
		StringBuilder string_builder;
		string_builder << ContentLibrary::_content_path << "/" << in_local_path;
		string_builder >> result;
        return result;
    }

    String ContentLibrary::getRelativePath(const String& in_abso_path)
    {
        if( !_given_env_var )
        {
            return in_abso_path;
        }

        return String(in_abso_path, ContentLibrary::_content_path.length(), in_abso_path.length() - ContentLibrary::_content_path.length());
    }

    void ContentLibrary::initialize()
    {
		HHD_ASSERT(_num_types > 0);
        _logger = new Logger("logs/content_library.log");
        _content_table = new HashTable<String, SmartPtr<IContent> >[_num_types];
    }

    void ContentLibrary::printOut()
    {
        HashTable<String, SmartPtr<IContent> >* content_table;

        for( uint32_t type_index = 0; type_index < _num_types; type_index++ )
        {
            //iterate through each hash table
            content_table = &_content_table[type_index];
            IEnumerator< Pair< String, SmartPtr<IContent> > >& iter = content_table->getEnumerator();

            while(iter.moveNext())
            {
                hout << "Holding content path: " << iter.current().second->getPath() << " count: " << iter.current().second.queryRefCount() << endl << endl;
            }
        }
    }

    void ContentLibrary::finalize()
    {
        //iterate through all of the scenes and set ref counter to 0
        //the game is ending and should release all scenes
        HashTable<String, SmartPtr<IContent> >& scene_table = _content_table[TScene::contentID()];
		scene_table.clear();

#if HHD_DEBUG 
        ContentLibrary::printOut();
#	if HHD_PLATFORM_WINDOWS
        _ASSERTE( _CrtCheckMemory( ) );
#	endif
#endif

        delete[] _content_table;
        delete _logger;
    }

    /**
    * To be used by IGame solely to change scenes without increasing ref count
    */
    SmartPtr<TScene> ContentLibrary::getScene(const String& in_path)
    {
        SmartPtr<TScene> requested_scene = NULL;
		SmartPtr<IContent> query = NULL;

        _content_table[TScene::contentID()].tryGetValue(in_path, query);

		requested_scene = SmartPtr<IContent>::castTo<TScene>(query);
        return requested_scene;
    }

	bool ContentLibrary::releaseScene( const String& in_path )
	{
		return _content_table[TScene::contentID()].remove(in_path);
	}

    void ContentLibrary::loadAndParseAssetList(const String& in_path)
    {
        FileInputStream fis(in_path);

        StringBuilder sb;

        char8_t current;
        while (fis.read( current ))
        {
            sb << current;
        }
        fis.close();

		String xml_string;
		sb >> xml_string;

        TiXmlDocument document;
        document.Parse(xml_string);

        TiXmlElement* root_element = document.RootElement();
        String root_tag(root_element->Value());

        if(root_tag.equals("Root"))
        {
			for(TiXmlElement* child_element = root_element->FirstChildElement();
				child_element != NULL;
				child_element = child_element->NextSiblingElement())
			{
				const char8_t* tag = child_element->Value();
                if(String::equals(tag, "AssetList"))
                {
                    String new_xml(child_element->Attribute("path"));
                    ContentLibrary::loadAndParseAssetList(new_xml);
                }
                else if(String::equals(tag, "Content"))
                {
					String path = child_element->Attribute("path");
					String type = child_element->Attribute("type");
					ContentLibrary::loadContent(path, type);
                }
				else
				{
					HHD_ASSERT(!"Not Implemented");
				}
			}
        }
    }

	SmartPtr<IContent> ContentLibrary::loadContent( const String& in_path, const String& in_type )
	{
		uint32_t content_id;
		bool result = _type_to_id.tryGetValue(in_path, content_id);
		HHD_ASSERT(result == true);

		SmartPtr<IContent> potentially_stored;
		if(_content_table[content_id].tryGetValue(in_path, potentially_stored))
		{
			//already loaded, we're done
			return potentially_stored;
		}
		else
		{
			//new piece of content, needs to be loaded
			SmartPtr<IContent> new_content = Registry<IContent>::createFromRegistry(in_type);
			new_content->create(in_path);

			_content_table[content_id].add(in_path, new_content);

			return new_content;
		}
	}

}